package com.cskt.itripauth.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.entity.ItripUser;
import com.cskt.common.vo.ReturnResult;
import com.cskt.common.vo.TokenVo;
import com.cskt.itripauth.shiro.JWTUtil;
import com.cskt.itripauth.util.RedisUtil;
import com.cskt.service.ItripUserService;
import com.cskt.util.MD5;
import io.swagger.annotations.Api;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@RestController
public class LoginController {
    @Resource
    private ItripUserService itripUserService;
    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/doLogin")
    public ReturnResult doLogin(@RequestParam String username,
                                @RequestParam String password,
                                HttpServletRequest request){
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
            return ReturnResult.error(ErrorCodeEnum.AUTH_PARAMETER_ERROR);
        }
        //和数据库进行对比
        QueryWrapper<ItripUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_code", username);
        ItripUser user = itripUserService.getOne(queryWrapper);
        if (user == null) {
            return ReturnResult.error(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }
        //根据加密规则，用户输入密码进行加密，加密后的密码与数据库中的进行对比
        password=password+user.getCreatedBy().toString();
        password = MD5.getMd5(password, 32);
        //判断输入的密码加密后是否与数据库中保存的加密的密码是否一致


        System.out.println(password+"     :     "+user.getUserPassword());
        if (!password.equals(user.getUserPassword())) {
            return ReturnResult.error(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }
        //用户名和密码都正确就生成token
        String token=null;
        try {
            token = JWTUtil.sign(username, password);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        TokenVo tokenVo=new TokenVo(token,System.currentTimeMillis()*2*3600*1000,System.currentTimeMillis());
        redisUtil.set(token, JSON.toJSONString(user));
        redisUtil.expire(token, 2 * 60 * 60);
        return ReturnResult.ok(tokenVo);
    }
}
